package org.web.webdisplay.server.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.web.base.domain.ResultDO;
import org.web.base.domain.ViewResultHelper;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ServiceExceptionHelper;
import org.web.base.domain.view.ViewResultDTO;
import org.web.webdisplay.sdk.biz.DisplayInfoBiz;
import org.web.webdisplay.sdk.dto.DisplayInfoDTO;
import org.web.webdisplay.sdk.dto.UserPageQueryInfoDTO;
import org.web.webdisplay.sdk.dto.query.QueryDisplayInfoRequest;

import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import org.web.webdisplay.sdk.dto.query.QueryUserPageQueryInfoRequest;
import org.web.webdisplay.server.biz.impl.UserPageQueryInfoBizImpl;
import org.web.webdisplay.server.controller.query.DisplaySettingByUserRequest;
import org.web.webdisplay.server.domain.UserPageQueryInfoDO;
import org.web.webdisplay.server.domain.query.QueryUserPageQueryInfo;
import org.web.webdisplay.server.service.UserPageQueryInfoService;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;


@Controller("displaySetting")
@RequestMapping("displaySetting")
public class DisplaySettingController {

    private static final Logger logger = LogManager.getLogger(DisplaySettingController.class);

    @Resource
    private DisplayInfoBiz displayInfoBiz;

    @Resource
    private UserPageQueryInfoService userPageQueryInfoService;


    @Resource
    private UserPageQueryInfoBizImpl userPageQueryInfoBiz;

    @RequestMapping("selectDisplayInfo")
    @ResponseBody
    public ViewResultDTO<String> selectDisplayInfo(@RequestBody QueryDisplayInfoRequest queryDisplayInfoRequest) {

        ViewResultDTO<String> viewResultDTO = new ViewResultDTO<>(true);
        try {
            checkQueryDisplayInfo(queryDisplayInfoRequest);
            ResultDO<List<DisplayInfoDTO>> selectResult = displayInfoBiz.selectDisplayInfoList(queryDisplayInfoRequest);
            String value;
            if (selectResult.isSuccess()) {
                if (selectResult.getDomain() == null || selectResult.getDomain().isEmpty()) {
                    throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.DATA_NOT_EXIST);
                }
                value = selectResult.getDomain().getFirst().getDisplayInfo();
                viewResultDTO.setData(value);
            }
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            viewResultDTO = ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDTO;
    }

    @RequestMapping("selectDisplaySettingByUser")
    @ResponseBody
    public ViewResultDTO<String> selectDisplaySettingByUser(@RequestBody DisplaySettingByUserRequest displaySettingByUserRequest) {

        ViewResultDTO<String> viewResultDTO = new ViewResultDTO<>(true);
        try {
            QueryDisplayInfoRequest queryDisplayInfoRequest = displaySettingByUserRequest.getQueryDisplayInfoRequest();
            checkQueryDisplayInfo(queryDisplayInfoRequest);
            ResultDO<List<DisplayInfoDTO>> selectResult = displayInfoBiz.selectDisplayInfoList(queryDisplayInfoRequest);
            String value;
            if (selectResult.isSuccess()) {
                if (selectResult.getDomain() == null || selectResult.getDomain().isEmpty()) {
                    throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.DATA_NOT_EXIST);
                }
                value = selectResult.getDomain().getFirst().getDisplayInfo();
                if (StringUtils.isNotEmpty(displaySettingByUserRequest.getUserId())) {
                    QueryUserPageQueryInfo queryUserPageQueryInfo = new QueryUserPageQueryInfo();
                    queryUserPageQueryInfo.setUserId(displaySettingByUserRequest.getUserId());
                    queryUserPageQueryInfo.setDisplayInfoId(displaySettingByUserRequest.getQueryDisplayInfoRequest().getDisplayInfoId());
                    if (StringUtils.isEmpty(displaySettingByUserRequest.getQueryName())) {
                        queryUserPageQueryInfo.setQueryName(QueryUserPageQueryInfo.DEFAULT_QUERY_NAME);
                    } else {
                        queryUserPageQueryInfo.setQueryName(displaySettingByUserRequest.getQueryName());
                    }
                    UserPageQueryInfoDO userPageQueryInfoDO = userPageQueryInfoService.selectOneUserPageQueryInfo(queryUserPageQueryInfo);
                    if (userPageQueryInfoDO != null && userPageQueryInfoDO.getQueryInfo() != null) {
                        try {
                            String queryInfo = userPageQueryInfoDO.getQueryInfo();
                            Gson gson = new Gson();
                            Map<String, String> queryInfoMap = gson.fromJson(queryInfo, Map.class);
                            JsonArray jsonArray = gson.fromJson(value, JsonArray.class);
                            if (!queryInfoMap.isEmpty()) {
                                for (JsonElement element : jsonArray) {
                                    JsonObject fieldObj = element.getAsJsonObject();
                                    String queryAttributeName = fieldObj.get("queryAttributeName").getAsString();
                                    Object queryValue = queryInfoMap.get(queryAttributeName);
                                    if (queryValue != null) {
                                        fieldObj.addProperty("queryAttributeDefaultValue", queryValue.toString());
                                    }
                                }
                                value = jsonArray.toString();
                            }
                        } catch (Exception e) {
                            // 出现异常，可以忽略，不影响显示设置的查询结果。
                            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
                        }
                    }
                }
                viewResultDTO.setData(value);
            }
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            viewResultDTO = ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDTO;
    }

    @RequestMapping("selectUserPageQueryInfoList")
    @ResponseBody
    public ViewResultDTO<List<UserPageQueryInfoDO>> selectUserPageQueryInfoList(@RequestBody QueryUserPageQueryInfoRequest queryUserPageQueryInfoRequest) {
        ViewResultDTO<List<UserPageQueryInfoDO>> viewResultDTO = new ViewResultDTO<>(true);
        try {
            if (queryUserPageQueryInfoRequest.getUserId() == null || queryUserPageQueryInfoRequest.getDisplayInfoId() == null) {
                throw new IllegalArgumentException("用户ID和显示信息ID不能为空。");
            }
            QueryUserPageQueryInfo queryUserPageQueryInfo = new QueryUserPageQueryInfo();
            queryUserPageQueryInfo.setDisplayInfoId(queryUserPageQueryInfoRequest.getDisplayInfoId());
            queryUserPageQueryInfo.setUserId(queryUserPageQueryInfoRequest.getUserId());
            queryUserPageQueryInfo.setSpecifiedAttributeSet(new HashSet<>(Arrays.asList("user_page_query_info_id", "query_name", "query_info")));
            queryUserPageQueryInfo.setAllRecords();
            queryUserPageQueryInfo.setOrderByClause(" page_name desc");
            List<UserPageQueryInfoDO> selectResult = userPageQueryInfoService.selectUserPageQueryInfoList(queryUserPageQueryInfo);
            if (selectResult != null && !selectResult.isEmpty()) {
                viewResultDTO.setData(selectResult);
            }
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            viewResultDTO = ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDTO;
    }


    @RequestMapping("saveUserPageQueryInfo")
    @ResponseBody
    public ViewResultDTO<UserPageQueryInfoDTO> saveUserPageQueryInfo(@RequestBody UserPageQueryInfoDTO userPageQueryInfoDTO) {
        try {
            ResultDO<UserPageQueryInfoDTO> saveResult = userPageQueryInfoBiz.saveUserPageQueryInfo(userPageQueryInfoDTO);
            ResultDO<UserPageQueryInfoDTO> resultDO = new ResultDO<>();
            if (saveResult.isSuccess()) {
                resultDO.setDomain(saveResult.getDomain());
                return ViewResultHelper.convertToViewResultByResultDO(resultDO, UserPageQueryInfoDTO.class);
            } else {
                return ViewResultHelper.convertToViewResultByResultDO(saveResult, UserPageQueryInfoDTO.class);
            }
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            return ViewResultHelper.buildViewResultByServiceException(e, null);
        }
    }

    private void checkQueryDisplayInfo(@NotNull QueryDisplayInfoRequest queryDisplayInfoRequest) {

        if (queryDisplayInfoRequest == null) {
            throw new IllegalArgumentException("查询条件不能为空。");
        }
        if (queryDisplayInfoRequest.getDisplayInfoId() == null && StringUtils.isEmpty(queryDisplayInfoRequest.getIntlLanguage())) {
            queryDisplayInfoRequest.setIntlLanguage("zh");
        }

        if (queryDisplayInfoRequest.getDisplayInfoId() == null
                && (StringUtils.isEmpty(queryDisplayInfoRequest.getAppName())
                || StringUtils.isEmpty(queryDisplayInfoRequest.getPageName()))) {
            throw new IllegalArgumentException("主键、应用名称和页面名称不同时为空。");
        }

        queryDisplayInfoRequest.setFirstRecord();
    }

}
